package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.CounselorClass;
import com.example.chamberlainserver.Service.CounselorClassService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.CounselorClassDTO;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 辅导员班级关联管理控制器
 */
@RestController
@RequestMapping("/counselor-classes")
@Validated
public class CounselorClassController {

    @Autowired
    private CounselorClassService counselorClassService;

    /**
     * 查询所有关联关系
     */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<List<CounselorClass>>> getAllCounselorClasses() {
        try {
            List<CounselorClass> counselorClasses = counselorClassService.getAllCounselorClasses();
            return ResponseEntity.ok(ApiResponse.success("获取所有关联关系成功", counselorClasses));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询关联关系列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID查询关联关系
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<CounselorClass>> getCounselorClassById(@PathVariable @NotNull Long id) {
        try {
            CounselorClass counselorClass = counselorClassService.getCounselorClassById(id);
            if (counselorClass != null) {
                return ResponseEntity.ok(ApiResponse.success("查询关联关系成功", counselorClass));
            } else {
                return ResponseEntity.ok(ApiResponse.error("关联关系不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 根据辅导员ID查询关联关系
     */
    @GetMapping("/counselor/{counselorId}")
    public ResponseEntity<ApiResponse<List<CounselorClass>>> getCounselorClassesByCounselorId(@PathVariable @NotNull Long counselorId) {
        try {
            List<CounselorClass> counselorClasses = counselorClassService.getCounselorClassesByCounselorId(counselorId);
            return ResponseEntity.ok(ApiResponse.success("查询辅导员关联关系成功", counselorClasses));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询辅导员关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 根据班级ID查询关联关系
     */
    @GetMapping("/class/{classId}")
    public ResponseEntity<ApiResponse<List<CounselorClass>>> getCounselorClassesByClassId(@PathVariable @NotNull Long classId) {
        try {
            List<CounselorClass> counselorClasses = counselorClassService.getCounselorClassesByClassId(classId);
            return ResponseEntity.ok(ApiResponse.success("查询班级关联关系成功", counselorClasses));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询班级关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 查询特定辅导员和班级的关联关系
     */
    @GetMapping("/counselor/{counselorId}/class/{classId}")
    public ResponseEntity<ApiResponse<CounselorClass>> getCounselorClassByCounselorAndClass(
            @PathVariable @NotNull Long counselorId, 
            @PathVariable @NotNull Long classId) {
        try {
            CounselorClass counselorClass = counselorClassService.getCounselorClassByCounselorAndClass(counselorId, classId);
            if (counselorClass != null) {
                return ResponseEntity.ok(ApiResponse.success("查询关联关系成功", counselorClass));
            } else {
                return ResponseEntity.ok(ApiResponse.error("关联关系不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询关联关系（带详细信息）
     */
    @GetMapping("/page")
    public ResponseEntity<ApiResponse<PageResult<CounselorClass>>> getCounselorClassesByPageWithDetails(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String counselorName,
            @RequestParam(required = false) String className,
            @RequestParam(required = false) String department) {
        try {
            PageResult<CounselorClass> result = counselorClassService.getCounselorClassesByPageWithDetails(
                    page, size, counselorName, className, department);
            return ResponseEntity.ok(ApiResponse.success("分页查询关联关系成功", result));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("分页查询关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 创建关联关系
     */
    @PostMapping
    public ResponseEntity<ApiResponse<CounselorClass>> createCounselorClass(@RequestBody @Valid CounselorClassDTO counselorClassDTO) {
        try {
            // 检查关联关系是否已存在
            if (counselorClassService.existsCounselorClass(counselorClassDTO.getCounselorId(), counselorClassDTO.getClassId())) {
                return ResponseEntity.ok(ApiResponse.error("该辅导员已关联此班级"));
            }
            
            CounselorClass counselorClass = counselorClassService.createCounselorClass(counselorClassDTO);
            return ResponseEntity.ok(ApiResponse.success("创建关联关系成功", counselorClass));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("创建关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 批量创建关联关系
     */
    @PostMapping("/batch")
    public ResponseEntity<ApiResponse<String>> createCounselorClasses(@RequestBody @Valid List<CounselorClassDTO> counselorClassDTOs) {
        try {
            int createdCount = counselorClassService.createCounselorClasses(counselorClassDTOs);
            return ResponseEntity.ok(ApiResponse.success("批量创建关联关系成功", "成功创建 " + createdCount + " 个关联关系"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量创建关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 更新关联关系
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<CounselorClass>> updateCounselorClass(@PathVariable @NotNull Long id, 
                                                     @RequestBody @Valid CounselorClassDTO counselorClassDTO) {
        try {
            // 验证关联关系是否存在
            CounselorClass existingCounselorClass = counselorClassService.getCounselorClassById(id);
            if (existingCounselorClass == null) {
                return ResponseEntity.ok(ApiResponse.error("关联关系不存在"));
            }
            
            CounselorClass counselorClass = counselorClassService.updateCounselorClass(id, counselorClassDTO);
            return ResponseEntity.ok(ApiResponse.success("更新关联关系成功", counselorClass));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 删除关联关系
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteCounselorClass(@PathVariable @NotNull Long id) {
        try {
            boolean success = counselorClassService.deleteCounselorClass(id);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除关联关系成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除失败，关联关系不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 根据辅导员ID删除关联关系
     */
    @DeleteMapping("/counselor/{counselorId}")
    public ResponseEntity<ApiResponse<String>> deleteCounselorClassesByCounselorId(@PathVariable @NotNull Long counselorId) {
        try {
            int deletedCount = counselorClassService.deleteCounselorClassesByCounselorId(counselorId);
            return ResponseEntity.ok(ApiResponse.success("删除辅导员关联关系成功", "成功删除 " + deletedCount + " 个关联关系"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除辅导员关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 根据班级ID删除关联关系
     */
    @DeleteMapping("/class/{classId}")
    public ResponseEntity<ApiResponse<String>> deleteCounselorClassesByClassId(@PathVariable @NotNull Long classId) {
        try {
            int deletedCount = counselorClassService.deleteCounselorClassesByClassId(classId);
            return ResponseEntity.ok(ApiResponse.success("删除班级关联关系成功", "成功删除 " + deletedCount + " 个关联关系"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除班级关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 删除特定辅导员和班级的关联关系
     */
    @DeleteMapping("/counselor/{counselorId}/class/{classId}")
    public ResponseEntity<ApiResponse<String>> deleteCounselorClassByCounselorAndClass(
            @PathVariable @NotNull Long counselorId, 
            @PathVariable @NotNull Long classId) {
        try {
            boolean success = counselorClassService.deleteCounselorClassByCounselorAndClass(counselorId, classId);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除关联关系成功", "删除成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除失败，关联关系不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 批量删除关联关系
     */
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<String>> deleteCounselorClasses(@RequestBody @NotEmpty List<Long> ids) {
        try {
            int deletedCount = counselorClassService.deleteCounselorClasses(ids);
            return ResponseEntity.ok(ApiResponse.success("批量删除关联关系成功", "成功删除 " + deletedCount + " 个关联关系"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量删除关联关系失败: " + e.getMessage()));
        }
    }

    /**
     * 设置主要负责辅导员
     */
    @PatchMapping("/counselor/{counselorId}/class/{classId}/primary")
    public ResponseEntity<ApiResponse<String>> setPrimaryCounselor(@PathVariable @NotNull Long counselorId, 
                                            @PathVariable @NotNull Long classId) {
        try {
            boolean success = counselorClassService.setPrimaryCounselor(counselorId, classId);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("设置主要负责辅导员成功", "设置主要负责辅导员成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("设置失败，关联关系不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("设置主要负责辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 取消班级的主要负责辅导员
     */
    @DeleteMapping("/class/{classId}/primary")
    public ResponseEntity<ApiResponse<String>> clearPrimaryCounselor(@PathVariable @NotNull Long classId) {
        try {
            boolean success = counselorClassService.clearPrimaryCounselor(classId);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("取消主要负责辅导员成功", "取消主要负责辅导员成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("取消失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("取消主要负责辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 批量分配辅导员到班级
     */
    @PostMapping("/assign/counselor/{counselorId}")
    public ResponseEntity<ApiResponse<String>> assignCounselorToClasses(
            @PathVariable @NotNull Long counselorId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            @SuppressWarnings("unchecked")
            List<Long> classIds = (List<Long>) requestBody.get("classIds");
            Boolean isPrimary = (Boolean) requestBody.get("isPrimary");
            
            if (classIds == null || classIds.isEmpty()) {
                return ResponseEntity.ok(ApiResponse.error("班级ID列表不能为空"));
            }
            
            int assignedCount = counselorClassService.assignCounselorToClasses(counselorId, classIds, 
                    isPrimary != null && isPrimary);
            return ResponseEntity.ok(ApiResponse.success("批量分配辅导员成功", "成功分配 " + assignedCount + " 个班级"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量分配辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 批量分配班级到辅导员
     */
    @PostMapping("/assign/class/{classId}")
    public ResponseEntity<ApiResponse<String>> assignClassToCounselors(
            @PathVariable @NotNull Long classId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            @SuppressWarnings("unchecked")
            List<Long> counselorIds = (List<Long>) requestBody.get("counselorIds");
            Long primaryCounselorId = requestBody.get("primaryCounselorId") != null ? 
                    ((Number) requestBody.get("primaryCounselorId")).longValue() : null;
            
            if (counselorIds == null || counselorIds.isEmpty()) {
                return ResponseEntity.ok(ApiResponse.error("辅导员ID列表不能为空"));
            }
            
            int assignedCount = counselorClassService.assignClassToCounselors(classId, counselorIds, primaryCounselorId);
            return ResponseEntity.ok(ApiResponse.success("批量分配班级成功", "成功分配 " + assignedCount + " 个辅导员"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量分配班级失败: " + e.getMessage()));
        }
    }

    /**
     * 获取辅导员负责的班级数量
     */
    @GetMapping("/counselor/{counselorId}/count")
    public ResponseEntity<ApiResponse<Integer>> getClassCountByCounselorId(@PathVariable @NotNull Long counselorId) {
        try {
            int count = counselorClassService.getClassCountByCounselorId(counselorId);
            return ResponseEntity.ok(ApiResponse.success("查询班级数量成功", count));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询班级数量失败: " + e.getMessage()));
        }
    }

    /**
     * 获取班级的辅导员数量
     */
    @GetMapping("/class/{classId}/count")
    public ResponseEntity<ApiResponse<Integer>> getCounselorCountByClassId(@PathVariable @NotNull Long classId) {
        try {
            int count = counselorClassService.getCounselorCountByClassId(classId);
            return ResponseEntity.ok(ApiResponse.success("查询辅导员数量成功", count));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询辅导员数量失败: " + e.getMessage()));
        }
    }

    /**
     * 获取班级的主要负责辅导员
     */
    @GetMapping("/class/{classId}/primary")
    public ResponseEntity<ApiResponse<CounselorClass>> getPrimaryCounselorByClassId(@PathVariable @NotNull Long classId) {
        try {
            CounselorClass counselorClass = counselorClassService.getPrimaryCounselorByClassId(classId);
            if (counselorClass != null) {
                return ResponseEntity.ok(ApiResponse.success("查询主要负责辅导员成功", counselorClass));
            } else {
                return ResponseEntity.ok(ApiResponse.error("该班级暂无主要负责辅导员"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询主要负责辅导员失败: " + e.getMessage()));
        }
    }
}